﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGISExplorer.Data;
using System.Net;
using System.Xml;
using System.IO;

namespace TrackPoint.Data
{
    public class GeoNamesDatabase : IGeoDatabase
    {
        WebClient client;
        string tempXmlPath;
        List<SearchResult> results;

        public ICollection<SearchResult> Query(string value)
        {
            tempXmlPath = Path.GetTempFileName();
            string url = String.Format("http://ws.geonames.org/search?q={0}&maxRows=10&style=full", value);
            client.DownloadFile(url, tempXmlPath);
            return results;
        }

        public GeoNamesDatabase()
        {
            client = new WebClient();
            client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
        }

        private void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            results = new List<SearchResult>();

            XmlDocument doc = new XmlDocument();
            doc.Load(tempXmlPath);
            
            foreach (XmlNode node in doc.SelectNodes("/geonames/geoname"))
            {
                SearchResult result = new SearchResult();
                result.Title = node.SelectSingleNode("name").InnerText;
                result.Latitude = double.Parse(node.SelectSingleNode("lat").InnerText);
                result.Longitude = double.Parse(node.SelectSingleNode("lon").InnerText);
                result.Elevation = double.NaN;

                results.Add(result);
            }
        }
    }
}
